package com.atguigu.util;

import org.apache.commons.beanutils.BeanUtils;
import com.google.common.base.CaseFormat;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class PhoenixUtil {
    public static void sqlExecute(Connection connection,String sql){
        PreparedStatement ps=null;
        try {
            ps= connection.prepareStatement(sql);
            ps.execute();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            if(ps!=null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public static <T> List<T> sqlQuery(Connection connection, String sql, Class<T> clazz) {
        PreparedStatement preparedStatement = null;
        ArrayList<T> arrayList = new ArrayList<>();
        try {
            preparedStatement = connection.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData();
            // 使用反射创建对象
            while (resultSet.next()) {
                T t = clazz.newInstance();
                for (int i = 1; i <= metaData.getColumnCount(); i++) {
                    // columnName的类型是大写加_   转换为小驼峰
                    String columnName = metaData.getColumnName(i);
                    String propertyName = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, columnName);
                    String columnValue = resultSet.getString(i);
                    BeanUtils.setProperty(t,propertyName,columnValue);
                }
                arrayList.add(t);
            }
        }catch (Exception e){
            e.printStackTrace();
        } finally{
            if (preparedStatement != null){
                try {
                    preparedStatement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        return arrayList;
    }
}
